package com.wms.config;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import org.apache.shiro.codec.Base64;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.CookieRememberMeManager;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.servlet.SimpleCookie;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @Description:
 * @Project:
 * @CreateDate: Created in 2020/3/17 20:38
 * @Author: YXH
 */
@Configuration
public class ShiroConfig {

    /**
     添加shiro的内置过滤器
     anon: 无需认证就可访问
     authc：必须认证才能访问
     user：必须拥有记住我功能才能访问
     perms: 拥有对某个资源的权限才能访问
     role:拥有某个角色权限才能访问
     */
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager")DefaultWebSecurityManager defaultWebSecurityManager){
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
        //设置安全管理器
        bean.setSecurityManager(defaultWebSecurityManager);

        Map<String, String> filterMap = new LinkedHashMap<>();

        filterMap.put("/order/*","authc");
        filterMap.put("/index","authc");
        filterMap.put("/admin/*","authc");
        filterMap.put("/wine/*","authc");
        filterMap.put("/common/*","authc");
        filterMap.put("/member/*","authc");
        filterMap.put("/order/*","authc");
        filterMap.put("/admin/*","perms[superAdmin]");

        filterMap.put("/logout","logout");


        bean.setFilterChainDefinitionMap(filterMap);

        //设置登录请求
        bean.setLoginUrl("/toLogin");

        return bean;
    }

    @Bean(name="securityManager")
    public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        //关联UserRealm
        securityManager.setRealm(userRealm);
        //注入记住我管理器
        securityManager.setRememberMeManager(rememberMeManager());

        return securityManager;
    }

    @Bean(name = "userRealm")
    public UserRealm userRealm(){
        return new UserRealm();
    }

    @Bean
    public ShiroDialect getShiroDialect(){
        return new ShiroDialect();
    }

    @Bean
    public SimpleCookie rememberMeCookie(){
        return new SimpleCookie("userCookie");
    }


    @Bean
    public CookieRememberMeManager rememberMeManager(){
        CookieRememberMeManager cookieRememberMeManager = new CookieRememberMeManager();
        cookieRememberMeManager.setCookie(rememberMeCookie());
        cookieRememberMeManager.setCipherKey(Base64.decode("2AvVhdsgUs0FSA3SDFAdag=="));
        return cookieRememberMeManager;
    }
}
